#include "headfile/mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QTimer>
#include <QDateTime>
#include <QRadioButton>
#include <QListWidget>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QSqlRecord>
#include "headfile/myhelper.h"
#include "headfile/restcontrol.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->initStyle();
    this->initWidget();
}

MainWindow::~MainWindow()
{
    delete ui;
    delete spacer;
    delete exitAction;
    delete fullScreenAction;
    delete cargoAction;
    delete reportAction;
    delete settingAction;
    delete pTimer;
}

void MainWindow::initStyle()
{
    //设置默认打开最大化
    this->setWindowState(Qt::WindowMaximized);
    //主界面Title
    setWindowIcon(QIcon(":/image/logo.png"));
    setWindowTitle(QString("点餐系统"));
    //设置同时显示图标和文字
    ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    //设置toolbar不可移动
    ui->mainToolBar->setMovable(false);
    fullScreenState = false;    //全屏状态为false
    ui->tableLineEdit->setReadOnly(true);
    ui->usedLineEdit->setReadOnly(true);
    ui->freeLineEdit->setReadOnly(true);
}

void MainWindow::initWidget()
{
    this->addToolBarAct();
    this->initLCDNumber();
    this->createTimer();
    this->addTableTab();
}

//关闭事件, 关闭之前的提示框
void MainWindow::closeEvent(QCloseEvent *event)
{
    int result = myHelper::ShowMessageBoxQuesion("真的要关闭吗?");
    if (result == 1) {
        event->accept();
    } else {
        event->ignore();
    }
}

//设置LCDNumber进行时间显示
void MainWindow::initLCDNumber()
{
    // 设置能显示的位数
    ui->lcdNumber->setDigitCount(25);
    // 设置显示的模式为十进制
    ui->lcdNumber->setMode(QLCDNumber::Dec);
    // 设置显示外观
    //设置数字字体：Outline,轮廓突出，颜色为背景色；Filled，内部填充型，颜色为黑色；Flat,平面型
    ui->lcdNumber->setSegmentStyle(QLCDNumber::Flat);
    // 设置样式
    ui->lcdNumber->setStyleSheet("border: 0px; color: darkblue; background: transparent;");
}

//创建计时器并连接信号槽
void MainWindow::createTimer()
{
    pTimer = new QTimer(this);
    //设置定时间隔
    pTimer->setInterval(1000);
    //信号槽阻塞前先执行一次
    this->myslot_TimeOut();
    connect(pTimer, SIGNAL(timeout()), this, SLOT(myslot_TimeOut()));
    // 启动定时器
    pTimer->start();
}

//显示时间到lcdNumber中
void MainWindow::showTimeToLCD()
{
    // 获取系统当前时间
    QDateTime dateTime = QDateTime::currentDateTime();
    // 显示的内容
    ui->lcdNumber->display(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
}

//往tableTabWidget中添加tab
void MainWindow::addTableTab()
{
    int roomType, roomNo = 0;
    restcontrol restctl;
    QMap<int, QString> areatypeMap;

    ui->tableTabWidget->setStyleSheet(
                "QTabBar::tab { background: LightBlue; height: 30px;"
                    " width:80px; color:black; padding:3px; margin: 0px 1px; "
                    " font:14px Times New Roman;"
                    " border-radius:5px; border-width: 2px}"
                "QTabBar::tab:selected { background: CornflowerBlue; "
                    " font:bold; font-size: 14px Times New Roman;"
                    " border-radius:5px; border-width: 2px}" );

    ui->tableTabWidget->setTabText(0, QString("欢迎页"));

    //全部餐台tab
    QListWidget *listWidget1 = new QListWidget();

    this->addButtonToList(0, listWidget1);
    ui->tableTabWidget->addTab(listWidget1, QString("全部餐台")) ;

    //获取区域类型
    restctl.getTableAreaType(&areatypeMap);

    //迭代器
    QMap<int,QString>::iterator areatypeIt;
    roomNo = 0;
    for (areatypeIt = areatypeMap.begin(); areatypeIt != areatypeMap.end(); ++areatypeIt) {
        roomType = areatypeIt.key();
        QListWidget *listWidget = new QListWidget();

        this->addButtonToList(roomType, listWidget);
        ui->tableTabWidget->addTab(listWidget, areatypeIt.value());

        roomNo++;
    }
    areatypeMap.clear();
    //delete listWidget;
}

//往listWidget中添加内容
void MainWindow::addButtonToList(int roomType, QListWidget *listWidget)
{
    restcontrol restctl;
    QSqlRecord tableRecord;
    QSqlQueryModel *sqlModTables = new QSqlQueryModel();
    QString tableInfo;
    QString areaName;
    QString diningStatusName;
    int areatype;
    int diningStatus;
    QMap<int, QString> areaNameMap;


    listWidget->setViewMode(QListView::IconMode);   //设置图片排列
    listWidget->setWrapping(true);  // 自动换行？
    listWidget->setResizeMode(QListView::Adjust);  // 自动调整排列
    //listWidget->setGridSize(QSize(200,175));  // item 的大小
    //listWidget->setUniformItemSizes(true);  // 所有的 item 一样大
    listWidget->setSpacing(20); //item之间的间隔
    listWidget->setMovement(QListView::Static); //设置listwidget中的按钮不准拖动
    listWidget->setFlow(QListView::LeftToRight);    //qt给的demo中configdialog的例子中默认是竖向的
    listWidget->setIconSize(QSize(70, 70)); //设置item图标大小

    //设置样式，直接在函数中设置。给item加边框，后面给item设置的背景色会失效，为毛? 那就不加边框了
    listWidget->setStyleSheet(
                "QListWidget{border: 0px solid gray; color: black; }"
                "QListWidget::Item{padding-top: 7px; padding-bottom: 3px; }"
                "QListWidget::Item:hover{background: skyblue; padding-top: 5px; padding-bottom: 5px; }"
                "QListWidget::item:selected{color: red; padding-top: 5px; padding-bottom: 5px; }"
                );
    //"QListWidget::Item{padding-left: 15px; padding-right: 15px; }"
    //"QListWidget::Item{padding-top:10px; padding-bottom:4px; }"
    //"QListWidget::item:selected{background:lightblue; color:red; }"
    //"QListWidget::item:selected:!active{border-width:0px; background:lightgreen; }"


    // 获取数据库中的餐台信息，放到QSqlQueryModel中
    restctl.getTables(sqlModTables, roomType);
    restctl.getAreaName(&areaNameMap);

    for(int i = 0; i< sqlModTables->rowCount(); i++) {
        tableRecord = sqlModTables->record(i);
        tableInfo.clear();
        areaName.clear();
        diningStatusName.clear();
        QListWidgetItem *widgetItem = new QListWidgetItem();

        areatype = tableRecord.value("TableAreaId").toInt();
        areaName = areaNameMap.value(areatype);
        //0 :可供 1 :预订 2 :就餐 3 :脏台
        diningStatus = tableRecord.value("DiningStatus").toInt();
        switch(diningStatus)
        {
            case 0:
                diningStatusName.append("可供");
                widgetItem->setIcon(QIcon(":/image/table.png"));
                break;
            case 1:
                diningStatusName.append("预订");
                widgetItem->setIcon(QIcon(":/image/table_yuding.png"));
                widgetItem->setBackground(QBrush(Qt::blue));
                break;
            case 2:
                diningStatusName.append("就餐");
                widgetItem->setIcon(QIcon(":/image/table_jiucan.png"));
                widgetItem->setBackground(QBrush(Qt::green));
                break;
            case 3:
                diningStatusName.append("脏台");
                widgetItem->setIcon(QIcon(":/image/table_zangtai.png"));
                widgetItem->setBackground(QBrush(Qt::red));
                break;
            default:
                widgetItem->setIcon(QIcon(":/image/table.png"));
        }

        tableInfo = tableRecord.value("TableName").toString() + " "
                + QString("[%1人桌]").arg(tableRecord.value("Capability").toInt())
                + "\n[" + areaName + "] [" + diningStatusName + "]";
        widgetItem->setText(tableInfo);
        // widgetItem 中存入 TableID
        widgetItem->setData(Qt::UserRole, tableRecord.value("TableID"));
        listWidget->addItem(widgetItem);
    }
    //双击信号
    //connect(listWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT());
    //单击信号
    connect(listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(myslot_tableListWidgetItem_clicked(QListWidgetItem*)));
    delete sqlModTables;
    areaNameMap.clear();
}

//在 toolbar的右边添加action
void MainWindow::addToolBarAct()
{
    spacer = new QWidget();
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    // toolBar is a pointer to an existing toolbar
    ui->mainToolBar->addWidget(spacer);

    //插入分隔符
    ui->mainToolBar->addSeparator();

    // toolbar添加 货品action
    cargoAction = new QAction(QIcon(":/image/inbox.png"),tr("&货品"),this);
    cargoAction->setStatusTip(tr("货品"));
    ui->mainToolBar->addAction(cargoAction);
    // 连接到自定义槽
    connect(cargoAction, SIGNAL(triggered()), this, SLOT(myslot_cargoAction_triggered()));

    // toolbar添加 报表action
    reportAction = new QAction(QIcon(":/image/report.png"),tr("&报表"),this);
    reportAction->setStatusTip(tr("报表"));
    ui->mainToolBar->addAction(reportAction);
    connect(reportAction, SIGNAL(triggered()), this, SLOT(myslot_reportAction_triggered()));

    // toolbar添加 设置action
    settingAction = new QAction(QIcon(":/image/config.png"),tr("&设置"),this);
    settingAction->setStatusTip(tr("设置"));
    ui->mainToolBar->addAction(settingAction);
    connect(settingAction, SIGNAL(triggered()), this, SLOT(myslot_settingAction_triggered()));

    ui->mainToolBar->addSeparator();

    // toolbar添加 全屏action
    fullScreenAction = new QAction(QIcon(":/image/fullScreen.png"),tr("&全屏"),this);
    fullScreenAction->setStatusTip(tr("全屏"));
    ui->mainToolBar->addAction(fullScreenAction);
    connect(fullScreenAction, SIGNAL(triggered()), this, SLOT(myslot_fullScreenAction_triggered()));

    // 添加 退出action
    exitAction = new QAction(QIcon(":/image/system-log-out.png"),tr("&退出"),this);
    exitAction->setStatusTip(tr("退出系统"));
    ui->mainToolBar->addAction(exitAction);
    connect(exitAction, SIGNAL(triggered()), this, SLOT(myslot_exitAction_triggered()));
}

//定时器槽
void MainWindow::myslot_TimeOut()
{
    this->showTimeToLCD();
}

//锁屏action自定义槽
void MainWindow::on_lockScreenAction_triggered()
{

}

//退出action自定义槽
void MainWindow::myslot_exitAction_triggered()
{
    int result = myHelper::ShowMessageBoxQuesion("真的要关闭吗?");
    if (result == 1) {
        qApp->exit();
    }
}

//全屏action自定义槽
void MainWindow::myslot_fullScreenAction_triggered()
{
    if(!fullScreenState) {
        this->setWindowState(Qt::WindowFullScreen);
        fullScreenAction->setIcon(QIcon(":/image/outFull.png"));
        fullScreenAction->setText("退出全屏");
        fullScreenState = true;
    } else {
        this->setWindowState(Qt::WindowMaximized);
        fullScreenAction->setIcon(QIcon(":/image/fullScreen.png"));
        fullScreenAction->setText("全屏");
        fullScreenState = false;
    }
}

//货品action自定义槽
void MainWindow::myslot_cargoAction_triggered()
{

}

//报表action自定义槽
void MainWindow::myslot_reportAction_triggered()
{

}

//设置action自定义槽
void MainWindow::myslot_settingAction_triggered()
{

}

//点餐主页面餐台 ListWidget item单击时的槽
void MainWindow::myslot_tableListWidgetItem_clicked(QListWidgetItem *item)
{
    QSqlQueryModel billSqlMod;
    QString tableName;
    QString sTableStatus;
    QString billId;
    int iTableStatus;
    int tableid = item->data(Qt::UserRole).toInt();
    restcontrol restctl;
    QSqlRecord tableRecord;

    restctl.getOneTableInfo(&tableRecord, tableid);
    tableName.clear();
    tableName = tableRecord.value("TableName").toString()
            + "(" +
            tableRecord.value("TableCode").toString() + ")";
    ui->label_tablename->setText(tableName);

    sTableStatus.clear();
    iTableStatus = tableRecord.value("DiningStatus").toInt();
    switch(iTableStatus)
    {
        case 0:
            sTableStatus.append("[可供]");
            break;
        case 1:
            sTableStatus.append("[预订]");
            break;
        case 2:
            sTableStatus.append("[就餐]");
            break;
        case 3:
            sTableStatus.append("[脏台]");
            break;
    }
    ui->label_tablestatus->setStyleSheet("color: green");
    ui->label_tablestatus->setText(sTableStatus);

    //获取订单信息
    billId.clear();
    billId = tableRecord.value("DiningBillID").toString();
    //qDebug() << "billId: " << billId;
    restctl.getBillInfo(&billId, &billSqlMod);



}

void MainWindow::on_startPushButton_clicked()
{
    ui->tableTabWidget->setCurrentIndex(1);
}

void MainWindow::on_action_44_triggered()
{

}

